using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.AddressableAssets;
using UnityEditor.AddressableAssets.Settings;
using UnityEditor.AddressableAssets.Settings.GroupSchemas;
using UnityEngine;

namespace AddressablesTool
{
    /// <summary>
    /// Addressables组管理工具
    /// </summary>
    public static class AddressablesGroupManager
    {
        /// <summary>
        /// 检查Addressables设置是否存在
        /// </summary>
        /// <returns>设置是否存在</returns>
        public static bool HasAddressablesSettings()
        {
            return AddressableAssetSettingsDefaultObject.Settings != null;
        }

        /// <summary>
        /// 获取或创建Addressables组
        /// </summary>
        /// <param name="groupName">组名</param>
        /// <returns>Addressables组</returns>
        public static AddressableAssetGroup GetOrCreateGroup(string groupName)
        {
            var settings = AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null)
            {
                Debug.LogError("AddressableAssetSettings not found. Please create Addressables settings first.");
                return null;
            }

            // 查找现有组
            var group = settings.groups.FirstOrDefault(g => g.Name == groupName);

            // 如果组不存在，创建新组
            if (group == null)
            {
                group = settings.CreateGroup(groupName, false, false, false, null);

                // 添加BundledAssetGroupSchema
                var schema = group.AddSchema<BundledAssetGroupSchema>();
                schema.BuildPath.SetVariableByName(settings, "RemoteBuildPath");
                schema.LoadPath.SetVariableByName(settings, "RemoteLoadPath");

                Debug.Log($"Created new Addressables group: {groupName}");
            }

            return group;
        }

        /// <summary>
        /// 获取所有Addressables组名
        /// </summary>
        /// <returns>组名列表</returns>
        public static List<string> GetAllGroupNames()
        {
            var settings = AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null) return new List<string>();

            // 使用Addressables的API获取组名
            var groupNames = new List<string>();
            foreach (var group in settings.groups)
            {
                if (group != null && !string.IsNullOrEmpty(group.Name))
                {
                    groupNames.Add(group.Name);
                }
            }

            return groupNames;
        }

        /// <summary>
        /// 将资源添加到指定组
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <param name="groupName">组名</param>
        /// <returns>是否成功</returns>
        public static bool AddAssetToGroup(Object obj, string groupName)
        {
            if (obj == null)
            {
                Debug.LogError("Cannot add null object to Addressables group.");
                return false;
            }

            var path = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(path))
            {
                Debug.LogError($"Cannot get asset path for {obj.name}");
                return false;
            }

            var settings = AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null)
            {
                Debug.LogError("AddressableAssetSettings not found.");
                return false;
            }

            var group = GetOrCreateGroup(groupName);
            if (group == null)
            {
                Debug.LogError($"Failed to get or create group: {groupName}");
                return false;
            }

            var guid = AssetDatabase.AssetPathToGUID(path);

            // 检查资源是否已经在其他组中
            var existingEntry = settings.FindAssetEntry(guid);
            if (existingEntry != null)
            {
                // 如果资源已经在其他组中，使用MoveEntry方法移动到新组
                settings.MoveEntry(existingEntry, group);
                Debug.Log($"Moved asset {obj.name} from group {existingEntry.parentGroup?.Name} to group {groupName}");
            }
            else
            {
                // 创建新的Addressables条目
                var entry = settings.CreateOrMoveEntry(guid, group);
                if (entry != null)
                {
                    entry.address = path; // 使用路径作为地址
                    Debug.Log($"Added asset {obj.name} to group {groupName}");
                }
                else
                {
                    Debug.LogError($"Failed to create Addressables entry for {obj.name}");
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 批量将资源添加到指定组
        /// </summary>
        /// <param name="assets">资源列表</param>
        /// <param name="groupName">组名</param>
        /// <returns>成功添加的数量</returns>
        public static int AddAssetsToGroup(List<Object> assets, string groupName)
        {
            if (assets == null || assets.Count == 0)
            {
                Debug.LogWarning("No assets to add to Addressables group.");
                return 0;
            }

            int successCount = 0;

            foreach (var asset in assets)
            {
                if (AddAssetToGroup(asset, groupName))
                {
                    successCount++;
                }
            }

            Debug.Log($"Successfully added {successCount}/{assets.Count} assets to group {groupName}");
            return successCount;
        }

        /// <summary>
        /// 从组中移除资源
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <returns>是否成功</returns>
        public static bool RemoveAssetFromGroup(Object obj)
        {
            if (obj == null) return false;

            var path = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(path)) return false;

            var settings = AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null) return false;

            var guid = AssetDatabase.AssetPathToGUID(path);
            var entry = settings.FindAssetEntry(guid);

            if (entry != null)
            {
                // 使用RemoveAssetEntry方法移除资源
                var success = settings.RemoveAssetEntry(guid);
                if (success)
                {
                    Debug.Log($"Removed asset {obj.name} from Addressables");
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 检查资源是否在指定组中
        /// </summary>
        /// <param name="obj">资源对象</param>
        /// <param name="groupName">组名</param>
        /// <returns>是否在指定组中</returns>
        public static bool IsAssetInGroup(Object obj, string groupName)
        {
            if (obj == null) return false;

            var path = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(path)) return false;

            var settings = AddressableAssetSettingsDefaultObject.Settings;
            if (settings == null) return false;

            var guid = AssetDatabase.AssetPathToGUID(path);
            var entry = settings.FindAssetEntry(guid);

            return entry?.parentGroup?.Name == groupName;
        }
    }
}